/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.rpc.http.test;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import io.iec.edp.caf.commons.core.SerializerFactory;
import io.iec.edp.caf.commons.core.api.DataSerializer;
import io.iec.edp.caf.commons.core.enums.SerializeType;
import io.iec.edp.caf.commons.event.config.EventListenerSettings;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.rest.api.exception.RESTServiceExceptionMapper;
import io.iec.edp.caf.rpc.api.event.RpcClientEventBroker;
import io.iec.edp.caf.rpc.api.event.RpcServerEventBroker;
import io.iec.edp.caf.rpc.api.event.RpcServerEventManager;
import io.iec.edp.caf.rpc.api.service.InternalServiceManageService;
import io.iec.edp.caf.rpc.api.service.RpcServer;
import io.iec.edp.caf.rpc.api.utils.DefinitionUtil;
import io.iec.edp.caf.rpc.http.test.impl.ConstVirable;
import io.iec.edp.caf.rpc.http.test.impl.RpcTest;
import io.iec.edp.caf.rpc.http.test.impl.RpcTestImpl;
import io.iec.edp.caf.rpc.remote.http.api.RpcServiceApi;
import io.iec.edp.caf.rpc.remote.http.service.RpcServiceApiImpl;
import lombok.SneakyThrows;
import lombok.var;
import org.apache.cxf.Bus;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;

import static io.iec.edp.caf.rpc.http.test.impl.ConstVirable.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@Configuration
@EnableAutoConfiguration
@ComponentScan({"io.iec.edp.caf.rpc.http"})
public class RpcTestConfiguration {

    @Bean
    public RpcServerEventManager createRpcServerEventManager(){
        return new RpcServerEventManager();
    }

    @Bean
    public RpcServerEventBroker createRpcServerEventBroker(RpcServerEventManager manager, EventListenerSettings settings){
        return new RpcServerEventBroker(manager,settings);
    }

    @Bean
    public RpcClientEventBroker createClientEventBroker(){
        return mock(RpcClientEventBroker.class);
    }

    @Bean
    public EventListenerSettings createEventListenerSettings() {
        return mock(EventListenerSettings.class);
    }

    @Bean
    public RpcTest createRpcTest(){
        return  new RpcTestImpl();
    }

    @SneakyThrows
    @Bean
    public RpcServer createRpcServer(){
        RpcServer server = mock(RpcServer.class);
        return server;
    }

//    @Bean
//    public ICAFContextService createCAFContextService(){
//        ICAFContextService contextService = mock(ICAFContextService.class);
//        return contextService;
//    }
    @Bean
    public RpcServiceApi createRpcServerApi(Bus bus, RpcServer rpcServer, RpcServerEventBroker serverEventBroker,InternalServiceManageService manageService) {
        try(MockedStatic<SpringBeanUtils> beanUtils = Mockito.mockStatic(SpringBeanUtils.class)) {
//            beanUtils.when(() -> SpringBeanUtils.getBean(BizContextManager.class)).thenReturn(mock(BizContextManager.class));
            beanUtils.when(() -> SpringBeanUtils.getBean(InternalServiceManageService.class)).thenReturn(manageService);

            RpcServiceApi service = new RpcServiceApiImpl(rpcServer, serverEventBroker);
            //发布RESTService
            try {
                JAXRSServerFactoryBean endpoint = new JAXRSServerFactoryBean();
                endpoint.setAddress("/runtime/communication/v1.0/rpc");
                endpoint.setBus(bus);
                endpoint.setServiceBeans(Arrays.asList(service));
//            endpoint.setFeatures(new ArrayList<Feature>() {
//                {
//                    this.add(RESTEndpointUtil.buildLoggingFeature());
//                }
//            });
                final DataSerializer serializer = SerializerFactory.getSerializer(SerializeType.Json);
                endpoint.setProviders(new ArrayList<Object>() {
                    {
                        this.add(new JacksonJsonProvider((ObjectMapper)serializer.getObjectMapper()));
                        this.add(new RESTServiceExceptionMapper());
                    }
                });
//            if (interceptors != null && interceptors.size() > 0) {
//                endpoint.getInInterceptors().addAll(interceptors);
//            }

                endpoint.create();
            } catch (Throwable var6) {
                throw var6;
            }
//        RESTEndpointUtil.createJAXRSServerWithInterceptor("/runtime/communication/v1.0/rpc", bus,
//                Arrays.asList(service), Arrays.asList(new AuthorizingInterceptor()));
            return service;
        }


    }

    @Bean
    public InternalServiceManageService createInternalSvrManagement() {
        InternalServiceManageService service = mock(InternalServiceManageService.class);
        var serviceDefinition = DefinitionUtil.transformServiceDefinition(RpcTest.class);
        var temp = serviceDefinition.getMethods().stream().filter(x->x.getServiceId().equalsIgnoreCase(TestNoReturnRpc)).collect(Collectors.toList());
        TestNoReturnRpcDef = temp.get(0);
        when(service.getRpcMethodDefinition(ConstVirable.TestNoReturnRpc)).thenReturn(TestNoReturnRpcDef);

        var temp1 = serviceDefinition.getMethods().stream().filter(x->x.getServiceId().equalsIgnoreCase(TestReturnRpc)).collect(Collectors.toList());
        TestReturnRpcDef = temp1.get(0);
        when(service.getRpcMethodDefinition(TestReturnRpc)).thenReturn(TestReturnRpcDef);

        var temp2 = serviceDefinition.getMethods().stream().filter(x->x.getServiceId().equalsIgnoreCase(TestReturnWithCustomeSerializeRpc)).collect(Collectors.toList());
        TestReturnWithCustomeSerializeRpcDef = temp2.get(0);
        when(service.getRpcMethodDefinition(TestReturnWithCustomeSerializeRpc)).thenReturn(TestReturnWithCustomeSerializeRpcDef);

        var temp3 = serviceDefinition.getMethods().stream().filter(x->x.getServiceId().equalsIgnoreCase(TestDownloadFile)).collect(Collectors.toList());
        TestDownloadFileDef = temp3.get(0);
        when(service.getRpcMethodDefinition(TestDownloadFile)).thenReturn(TestDownloadFileDef);

        var temp4 = serviceDefinition.getMethods().stream().filter(x->x.getServiceId().equalsIgnoreCase(TestUploadFile)).collect(Collectors.toList());
        TestUploadFileDef = temp4.get(0);
        when(service.getRpcMethodDefinition(TestUploadFile)).thenReturn(TestUploadFileDef);

        return service;
    }

}
